import platform
import subprocess
import time

DEBUG_FEATURE_FLAG = False
JIEBA_LIB_DIR = 'jieba;jieba' if platform.system() == 'Windows' else 'jieba:jieba'


def installer():
    print('[INFO] Checking System State...', end='')
    if platform.system() == 'Darwin' or platform.system() == 'Windows':
        print('ok.')
        print('[INFO] Downloading requirements', end='')
        p = subprocess.Popen(
            ['pip', 'install', '-r', 'requirements.txt', '-i',
             'https://pypi.tuna.tsinghua.edu.cn/simple/'], stdout=subprocess.DEVNULL)
        while True:
            if p.poll() is None:
                time.sleep(0.1)
                print('.', end='')
                continue
            if p.poll() != 0:
                print('[ERROR] Failed to install requirements!')
            break
        print('ok.')
        print('[INFO] Building project', end='')
        if DEBUG_FEATURE_FLAG:
            p = subprocess.Popen(
                ['pyinstaller', '-F', 'main.py', '--hidden-import', 'jieba',
                 '--add-data', JIEBA_LIB_DIR])
        else:
            p = subprocess.Popen(
                ['pyinstaller', '-F', '--noconsole', 'main.py', '--hidden-import', 'jieba',
                 '--add-data', JIEBA_LIB_DIR])
        while True:
            if p.poll() is None:
                time.sleep(0.1)
                print('.', end='')
                continue
            break
        print('ok. See binary file at dist/')
        if platform.system() == 'Darwin':
            subprocess.Popen(['chmod', '+x', 'dist/main'], stdout=subprocess.DEVNULL)
    else:
        print('[ERROR] Your platform is not supported yet!')


if __name__ == '__main__':
    installer()
